package indoor.nexd.com.nexdmap.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import indoor.nexd.com.nexdmap.R;
import indoor.nexd.com.nexdmap.presenter.SignInPresenter;
import indoor.nexd.com.nexdmap.ui.BaseActivity;
import indoor.nexd.com.nexdmap.ui.inte.ISignInActivity;
import indoor.nexd.com.nexdmap.util.ProgressDialogUtils;
import indoor.nexd.com.nexdmap.view.AutoEmailEditText;
import indoor.nexd.com.nexdmap.view.CustomAutoCompleteTextView;

/**
 * A login screen that offers login via email/password.
 */
public class SignInActivity extends BaseActivity<SignInPresenter> implements EditText.OnEditorActionListener, View.OnClickListener, ISignInActivity {
    /**
     * 2013.3.15
     * 整理代码结构
     * 功能及bug：隐藏Scrollbars
     * 处理键盘下一项,点击空白处键盘关闭
     * 2013.3.16
     * 更改登录页UI
     */

    private InputMethodManager imm;
    // UI references.
    @Bind(R.id.email)
    AutoEmailEditText mEmailView;
    @Bind(R.id.password)
    EditText mPasswordView;
    @Bind(R.id.login_form)
    View mLoginFormView;
    @Bind(R.id.email_sign_in_button)
    Button mEmailSignInButton;
    @Bind(R.id.login_progress)
    ProgressBar mProgressView;
    @Bind(R.id.top_layout_back)
    ImageView imBack;

    TimerTask lockTask;
    Timer lockTimer;
    private boolean flag = false;
    boolean cancel = false;
    View focusView = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SignInPresenter.ERROR_LOGIN_COUNT_LESS:
                    mEmailSignInButton.setEnabled(true);
                    mEmailSignInButton.setBackgroundColor(getResources().getColor(R.color.btn_login_bg));
                    break;
            }
        }
    };

    public void initView() {
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        checkIsNetworkAvailable();
        imBack.setVisibility(View.GONE);
        mPasswordView = (EditText) findViewById(R.id.password);
        mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = (ProgressBar) findViewById(R.id.login_progress);
        mEmailView.setOnEditorActionListener(this);
        mPasswordView.setOnClickListener(this);
        mEmailSignInButton.setOnClickListener(this);
    }


    @Override
    public int getLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    public void initPresenter() {
        presenter = new SignInPresenter(this, this);
        presenter.init();
    }


    private void checkIsNetworkAvailable() {
        presenter.checkOpenWifi();
    }

    /*
    2016.3.15
    点击空白处隐藏输入法的处理
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = this.getCurrentFocus();
            if (isHiddenKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void hideKeyboard(IBinder token) {
        if (token != null) {
            imm.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private boolean isHiddenKeyboard(View v, MotionEvent ev) {
        if (v != null && v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom) {
                //点击了EditText就不需要处理
                return false;
            }

        }
        return true;
    }

    /*
    2016.3.17 xun
   验证用户名密码，获取用户配置项、支持的商场列表
    */
    private void doLogin() {
        mEmailView.setError(null);
        mPasswordView.setError(null);
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();
        int errorCode = presenter.validateMsg(email, password);
        if (errorCode == SignInPresenter.ERROR_PWD) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }
        if (errorCode == SignInPresenter.ERROR_EMAIL_EMPTY) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (errorCode == SignInPresenter.ERROR_EMAIL_VALIDATE) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            presenter.doLogin(email, password);
        }

    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (v.getId()) {
            case R.id.password:
                if (actionId == R.id.login) {
                    doLogin();
                    flag = true;
                }
                break;
            case R.id.email:
                flag = false;
                if (actionId == EditorInfo.IME_ACTION_NEXT) {
                    mPasswordView.requestFocus();
                    flag = true;
                }
                break;
        }
        return flag;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.email_sign_in_button:
                imm.hideSoftInputFromInputMethod(mLoginFormView.getWindowToken(), 0);
                cancel = false;
                doLogin();
                break;


        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    //View需要做的工作
    @Override
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showProgress(int visibility) {
        if (visibility == View.VISIBLE) {
            ProgressDialogUtils.showProgressDialog(this, "登录中......", "", false);
        } else if (visibility == View.GONE) {
            ProgressDialogUtils.dismissProgressDialog(this);
        }
    }

    @Override
    public void printLog(String tag, String msg, int type) {

    }


    @Override
    public void intoNextActivity() {
        Intent intent = new Intent(SignInActivity.this, MallListActivity.class);
        //  intent.putParcelableArrayListExtra("mallList", MyApplication.mallList);
        startActivity(intent);
        SignInActivity.this.finish();
    }

    @Override
    public void setLoginButtonStatus(int failCount) {
        if (failCount > 3) {
            mEmailSignInButton.setEnabled(false);
            mEmailSignInButton.setBackgroundColor(getResources().getColor(R.color.gray));
            Toast.makeText(this, getResources().getString(R.string.error_usernamepwd_count), Toast.LENGTH_SHORT).show();
            if (lockTimer == null && lockTask == null) {
                lockTimer = new Timer();
                lockTask = new TimerTask() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(1);
                    }
                };
                lockTimer.schedule(lockTask, 10000);
            }
        } else {
            if (lockTimer != null && lockTask != null) {
                lockTask.cancel();
                lockTask = null;
                lockTimer = null;
            }
        }
    }


}


